<!--
 * @ Author: hongjiazhun
 * @ Create Time: 2023-03-10 22:39:11
 * @ Modified by: hongjiazhun
 * @ Modified time: 2023-03-30 20:10:12
 * @ Description:秘书排班（填报）
 -->

<template>
  <div class="app-container">
    <input
      style="opacity: 0; display: none"
      ref="import"
      type="file"
      accept=".xlsx, .xls"
      @input="onImportEx"
    />
    <avue-crud
      ref="crud"
      v-model="form"
      @on-load="onLoad"
      :data="tableData"
      :page.sync="page"
      :option="option"
      :search.sync="searchParams"
      :table-loading="loading"
      @refresh-change="refreshChange"
      @size-change="sizeChange"
      @current-change="currentChange"
      @search-change="searchChange"
      @search-reset="resetChange"
    >
      <template slot-scope="{ row }" slot="complete">
        <el-tag v-if="row.complete" size="small" type="success">是</el-tag>
        <el-tag v-else size="small" type="danger">否</el-tag>
      </template>
      <!-- <template slot-scope="scope" slot="menuLeft">
        <el-button
          circle
          icon="el-icon-document-copy"
          size="small"
          title="导出"
        ></el-button>
        <el-button
          size="small"
          icon="el-icon-download"
          circle
          title="下载导入模板"
          @click="downloadTemplate"
        >
        </el-button>
      </template> -->

      <template slot-scope="{ row, type }" slot="menu">
        <el-popover placement="top" width="250" trigger="click">
          <div style="padding: 6px">
            <div style="font-weight: 700; padding-bottom: 1px">
              请选择排班日期
            </div>
            <el-date-picker
              popper-class="picker-popper"
              style="width: 100%"
              v-model="scheduleDay"
              type="date"
              placeholder="选择日期"
              :picker-options="getPickerOptions(row)"
              :defaultValue="new Date(row.startDate)"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
            <!-- <el-select style="width: 100%" v-model="value" placeholder="请选择">
              <el-option
                v-for="item in dateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select> -->
            <el-button
              type="primary"
              style="width: 100%; margin-top: 10px"
              @click="fillHandle"
              :disabled="scheduleDay === ''"
              >进入填报页面</el-button
            >
          </div>
          <el-button
            slot="reference"
            :type="type"
            icon="el-icon-edit"
            size="small"
            @click="selectDate(row)"
            >填报</el-button
          >
        </el-popover>

        <el-button
          :type="type"
          size="small"
          icon="el-icon-document-add"
          @click="importData(row)"
          style="margin-left: 10px"
        >
          导入</el-button
        >

        <el-button
          size="small"
          icon="el-icon-download"
          :type="type"
          title="下载导入模板"
          @click="downloadTemplate"
        >
          下载模板</el-button
        >
      </template>
    </avue-crud>

    <!-- 填报 -->
    <FillModule
      :row="selectRow"
      :scheduleDay="scheduleDay"
      v-if="showFillModule"
      @close="closeFillModule"
    ></FillModule>
  </div>
</template>

<script>
import FillModule from "./components/FillModule.vue";
// import XLSX from "xlsx";
import { getList, multiImportData } from "@/api/arrangeClasses/fillIn";
import { mapGetters } from "vuex";
import { bsaeUrl } from "@/config/index";
import { getToken } from "@/utils/auth";

export default {
  name: "fillIn",
  components: {
    FillModule,
  },
  data() {
    return {
      // 选中填报的行
      tableData: [],
      option: {
        border: true,
        columnBtn: false,
        delBtn: false,
        editBtn: false,
        addBtn: false,
        // selection: true,
        tip: false,
        // dialogDrag: true,
        searchMenuSpan: 4,
        menuWidth: 250,
        column: [
          {
            label: "年度",
            prop: "scheduleYear",
            type: "year",
            format: "yyyy",
            valueFormat: "yyyy",
          },
          {
            label: "排班类型",
            prop: "scheduleType",
            search: true,
            type: "select",
            searchSpan: 5,
            props: {
              label: "dictLabel",
              value: "dictValue",
            },
            dicUrl: `${bsaeUrl}/system/dict/data/list?dictType=xmu_schedule_type`,
            dicHeaders: {
              Authorization: "Bearer " + getToken(),
            },
            dicFormatter: (res) => {
              const { rows = [], code } = res;
              return code === 200 ? rows : [];
            },
          },
          {
            label: "开始时间",
            prop: "startDate",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
          },
          {
            label: "结束时间",
            prop: "endDate",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
          },
          {
            label: "是否填报",
            prop: "complete",
            slot: true,
            // type: "select",
            // dicData: [
            //   {
            //     label: "是",
            //     value: true,
            //   },
            //   {
            //     label: "否",
            //     value: false,
            //   },
            // ],
          },
        ],
      },
      page: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
      },
      loading: false,
      // 选择
      selectionData: [],
      form: {},
      // 搜索参数
      searchParams: {},
      // 排班时间
      scheduleDay: "",
      selectRow: {},
      showFillModule: false,
      visibleFill: false,
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  methods: {
    // 填报
    fillHandle() {
      this.showFillModule = true;
    },
    // 关闭填报页面
    closeFillModule(type = "cancel") {
      this.showFillModule = false;
      type === "confirm" && this.onLoad();
    },
    // 获取数据
    async onLoad() {
      this.loading = true;
      const { currentPage = 1, pageSize } = this.page;
      const { deptId } = this.userInfo;
      // 设置请求参数
      const params = {
        pageNum: currentPage,
        pageSize,
        deptID: deptId,
        ...this.searchParams,
      };
      const { code, rows = [], total } = await getList(params);
      this.tableData = code === 200 ? rows : [];
      this.loading = false;
      // 设置总条数
      this.page.total = total;
    },
    // 刷新
    refreshChange() {
      this.onLoad();
    },
    // 条数
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
    },
    // 页数
    currentChange(val) {
      this.page.currentPage = val;
    },
    resetChange(item) {
      this.onLoad();
    },
    searchChange(params, done) {
      this.onLoad();
      done();
    },
    // 计算时间范围
    getPickerOptions(row) {
      const { startDate, endDate, scheduleDeptTableList = [] } = row;
      const scheduleDayArr = scheduleDeptTableList.map((v) => v.scheduleDay);
      return {
        disabledDate(time) {
          return (
            time.getTime() > new Date(endDate).getTime() ||
            time.getTime() < new Date(startDate).getTime() - 3600 * 1000 * 24
          );
        },
        cellClassName: (time) => {
          const year = time.getFullYear();
          const month = time.getMonth() + 1;
          const date = time.getDate();
          const str = `${year}-${month < 10 ? `0${month}` : month}-${
            date < 10 ? `0${date}` : date
          }`;

          if (scheduleDayArr.includes(str)) {
            return "badge";
          }
        },
      };
    },
    // 点击选择日期
    selectDate(row) {
      this.scheduleDay = "";
      this.selectRow = row;
    },
    // 下载导入模板
    downloadTemplate() {
      let url = "/template.xlsx";
      let a = document.createElement("a");
      a.href = url;
      a.download = "template.xlsx";
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    // 导入触发
    importData(row) {
      this.selectRow = row;
      this.$refs.import.value = "";
      this.$refs.import.click();
    },
    // 导入
    async onImportEx(file) {
      const { files } = file.target;
      const { scheduleTableId } = this.selectRow;
      let params = new FormData();
      params.append("scheduleId", scheduleTableId);
      params.append("file", files[0]);
      const { code, msg } = await multiImportData(params);
      if (code === 200) {
        this.$message.success(msg);
        this.onLoad();
      }

      // const fileReader = new FileReader(); // 创建FileReader 对象 读取文件
      // fileReader.onload = (event) => {
      //   try {
      //     const { result } = event.target;
      //     // 二进制读取 excel表格对象
      //     const workList = XLSX.read(result, { type: "binary" });
      //     // 存储数据
      //     let data = [];
      //     for (let sheet in workList.Sheets) {
      //       if (workList.Sheets.hasOwnProperty(sheet)) {
      //         // 利用 sheet_to_json 方法将 excel 转成 json 数据
      //         data = data.concat(
      //           XLSX.utils.sheet_to_json(workList.Sheets[sheet])
      //         );
      //         // break; // 如果只取第一张表，就取消注释这行
      //       }
      //     }
      //     // 设置空值数组，处理过滤
      //     const empty = [null, "", undefined, NaN];
      //     // 最终获取到并且格式化后的 json 数据
      //     const tableData = data
      //       .map((item) => {
      //         return {
      //           leaderId: Number(item["领导编号"]),
      //           leaderName: item["领导姓名"] || "",
      //           leaderPhone: item["领导联系方式"] || "",
      //           scheduleDay: item["排班日期"] || "",
      //           userId: Number(item["职工号"]),
      //           userName: item["姓名"] || "",
      //           officialPhone: item["办公电话"] || "",
      //           phone: item["移动电话"] || "",
      //           remark: item["备注"] || "",
      //         };
      //       })
      //       .filter((v) => !empty.includes(v.userId));

      //     console.error("tableData", tableData);
      //     // 导入数据检测
      //     // this.checkImportData(tableData);
      //   } catch (error) {
      //     this.$message.error("导入失败!");
      //   }
      // };
      // fileReader.readAsBinaryString(files[0]);
    },
  },
};
</script>

<style lang="scss">
.picker-popper .el-date-table .available.badge::after {
  position: absolute;
  content: "";
  right: 4px;
  top: 4px;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: rgb(8, 189, 42);
}

.picker-popper .el-date-table .available::after {
  position: absolute;
  content: "";
  right: 4px;
  top: 4px;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: red;
}
</style>
